import glob
import os
import shutil
import time
import pandas as pd
import pysnooper
from DrissionPage.common import Keys
from login import login_ing
from page import get_page
from 判断是否有广告弹窗 import yes_or_no
from 筛选excel import excel
from GetDataOnly import get_data_only


def get_data(port, user_path, down_path, date, usernames):
    # 清空下载文件夹
    for root, dirs, files in os.walk(down_path):
        # 删除文件
        for file in files:
            file_path = os.path.join(root, file)
            os.remove(file_path)
    for x in range(100):
        page = get_page(port, user_path, down_path)
        tab_id = page.get_tab()
        try:
            page.get("https://fxg.jinritemai.com/ffa/multiShop")
            page.wait(5)
            if page('.auxo-btn auxo-btn-primary', timeout=2):
                page.quit()
                page.wait(3)
                page = get_page(port, user_path, down_path)
                page.get("https://fxg.jinritemai.com/login/common")
            if not page.eles(".index_roleItem__1-Hwe", timeout=1) and not (
                    page('.feige_headerIcon__3CdVk', timeout=1) or page.eles('接待', timeout=1)):
                login_ing(page, usernames)
            if page.s_eles('text=重试'):
                print('出现重试，登录信息异常')
                page.quit()
                break
            page.wait.ele_deleted('text=加载中', timeout=30)
            店铺eles = page.eles('@class^index_introName')
            店铺名_list = [i.text for i in 店铺eles]
            for 店铺名 in 店铺名_list:
                page.wait.ele_deleted('text=加载中', timeout=10)
                shop_name = '抖音小店-' + 店铺名
                # 如果存在该店铺要获取的数据文件则跳过该店铺
                if os.path.exists(f"C:\\抖音客服数据\\{date}\\{shop_name}.xlsx"):
                    continue
                print(shop_name)
                page(店铺名).click(by_js=True)
                page.wait.load_start()
                page.wait.doc_loaded()
                if page.eles('.feige_headerIcon__3CdVk', timeout=5):
                    page('.feige_headerIcon__3CdVk').click(by_js=True)
                elif page.eles('接待', timeout=2):
                    page('接待').click(by_js=True)
                else:
                    print('没有找到飞鸽入口')
                    df = pd.DataFrame()
                    df.to_excel(f"C:\\抖音客服数据\\{date}\\{shop_name}.xlsx")
                    page.get("https://fxg.jinritemai.com/ffa/multiShop")
                    continue
                page.wait(8)
                # 切换到最新打开的标签页
                tab = page.get_tab(page.latest_tab)
                yes_or_no(tab, page)
                tab("text=数据").click()
                page.wait(1)
                tab("text=客服数据").click.multi(2)
                tab("text=历史数据").click()
                tab.wait(3)
                tab('@placeholder=开始时间').input(date, clear=True)
                tab('@placeholder=结束时间').input(date, clear=True)
                tab.wait(1)
                tab.actions.key_down(Keys.ENTER)
                # tab("近1天",timeout=3).click()
                tab("text=查询").click()
                tab.wait(4)
                if not tab('@class:auxo-btn auxo-btn-dashed').states.is_enabled:
                    print('没有导出权限')
                    df = pd.DataFrame()
                    df.to_excel(f"C:\\抖音客服数据\\{date}\\{shop_name}.xlsx")
                    page.close_tabs(tab)
                    page.get("https://fxg.jinritemai.com/ffa/multiShop")
                    continue
                tab("text=导出报表").click(by_js=True)
                page.wait(3)
                # 获取文件夹中所有的.xlsx文件
                xlsx_files = glob.glob(os.path.join(down_path, "*.xlsx"))
                os.makedirs(f'C:\\抖音客服数据\\{date}', exist_ok=True)
                shutil.move(xlsx_files[0], f"C:\\抖音客服数据\\{date}\\{shop_name}.xlsx")
                excel(shop_name, date, f"C:\\抖音客服数据\\{date}\\{shop_name}.xlsx")
                page.close_tabs(tab)
                page.wait(1)
                page.get("https://fxg.jinritemai.com/ffa/multiShop")
        except Exception as e:
            print(e)
            page.close_tabs(tab_id, others=True)
            continue
        page.quit()
        return '成功'
    return '失败'
